const BASE_URL = 'https://mrt.yixiangzn.com'

// #ifdef MP-WEIXIN
export default function streamLoad(url, params, onChunkReceived, onHeadersReceived, success, fail, complete, timeout =
	180000) {
	const requestTask = uni.request({
		url: BASE_URL + url,
		responseType: "arraybuffer",
		timeout: timeout,
		method: 'POST',
		enableChunked: true,
		header: {
			'Accept-Language': 'zh-CN,zh;q=0.9',
			'token': uni.getStorageSync('token'),
			'content-type': 'application/x-www-form-urlencoded',
		},
		data: params,
		success: res => {
			success && success(res)
		},
		fail: res => {
			fail && fail(res)
		},
		complete: res => {
			complete && complete(res)
		}
	})

	requestTask.onHeadersReceived(res => {
		onHeadersReceived && onHeadersReceived(res)
	})

	requestTask.onChunkReceived(res => {
		onChunkReceived && onChunkReceived(arrayBufferToString(res))
	})
}
// #endif

// #ifndef MP-WEIXIN
export default function streamLoad(url, params, onChunkReceived, onHeadersReceived, success, fail, complete, timeout =
	180000) {
	url = BASE_URL + url
	const xhr = new XMLHttpRequest()
	xhr.open("POST", url, true)
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
	xhr.setRequestHeader('Accept-Language', 'zh-CN,zh;q=0.9')
	xhr.setRequestHeader('token', 'c290d50f-8cb6-4d21-ac49-0090ce6aff25')
	xhr.onprogress = res => onChunkReceived && onChunkReceived(xhr.responseText)
	xhr.onloadstart = res => onHeadersReceived && onHeadersReceived(xhr.responseText)
	xhr.onloadend = res => complete && complete(xhr.responseText)
	xhr.onload = res => success && success(xhr.responseText)
	xhr.onerror = res => fail && fail(xhr.responseText)
	const usp = new URLSearchParams(params)
	const query = usp.toString()
	xhr.send(query)
}
// #endif

function arrayBufferToString(res) {
	const uint8Array = new Uint8Array(res.data);
	let text = String.fromCharCode.apply(null, uint8Array);
	text = decodeURIComponent(escape(text));
	return text;
}